﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Xml;
using System.Collections.Generic;

public partial class TaoBaoApi_TB_DownOrder2 : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Page.Theme = BLL.Common.GetWSMThemes();
    }
    //public BS2.BSTaobaoAPI.BSTaobaoBussinessList _curBus
    //{
    //    set { ViewState["_curBus"] = value; }
    //    get
    //    {
    //        if (ViewState["_curBus"] != null)
    //        {
    //            return (BS2.BSTaobaoAPI.BSTaobaoBussinessList)ViewState["_curBus"];
    //        }
    //        else
    //        {
    //            return new BS2.BSTaobaoAPI.BSTaobaoBussinessList();
    //        }
    //    }
    //}
    BS2.BSTaobaoAPI.BSTaobaoBussinessList _curBus = new BS2.BSTaobaoAPI.BSTaobaoBussinessList();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string url = Request.Url.ToString();
            HttpRequest myRequest = new HttpRequest("url", url, url.Substring(url.IndexOf("?") + 1));
            string start = myRequest.Params["start"];
            string end = myRequest.Params["end"];
            string status = myRequest.Params["status"];
            string user = myRequest.Params["user"];
            if (user == null || user.Length == 0 || status == null || status.Length == 0)
                return;
            GetTradeList(start, end, status, user);
        }
    }
    #region 下载订单列表
    public struct GVTrade
    {
        public string status;
        public string buyer_nick;
        public string price;
        public string tid;
        public string created;
        public string num;
        public string title;
        public string note;
    }
   
    void GetTradeList(string start, string end, string status, string user)
    {
        string pass = new TBCommon().GetTBPsdbyZH(user);
        if (pass == null || pass.Length == 0)
            return;
        txtUser.Text = user;
        txtpass.Text = pass;
        string errMsg = null;
        string sessionId = null;
        int ret = 0;
        string appkey = new TaoBaoAPI().GetAppKey(user);
        string certcode = new TaoBaoAPI().GetCertCode(user);
        ret = new TaoBaoAPI().GetTBSessionId(Page, user, pass, appkey, ref errMsg, ref sessionId);
        if (ret != 0)
        {
            new TBCommon().ShowMessage(Page, errMsg);
            return;
        }
        txtSession.Text = sessionId;

        string[,] param = new string[,] { { "nick", user }, { "method", "taobao.trades.sold.get" }, 
            { "fields", "tid,status,buyer_nick,price,created,num,orders" },{"status",status},{"start_created",start},{"end_created",end}, 
            {"page_size","40"},{"page_no","1"},{ "v", "1.0" }, { "timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "format", "xml" },{"app_key",appkey}};
        if(status=="ALL")
            param = new string[,] { { "nick", user }, { "method", "taobao.trades.sold.get" }, 
            { "fields", "tid,status,buyer_nick,price,created,num,orders" },{"start_created",start},{"end_created",end}, 
            {"page_size","40"},{"page_no","1"},{ "v", "1.0" }, { "timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "format", "xml" },{"app_key",appkey}};


        try
        {
            
            _curBus = BS2.BSTaobaoAPI.BSTaobaoBussinessAPI.getTaobaoTrade(param, appkey, certcode, sessionId);//取到记录数
            if (_curBus.Count < 1)
            {
                new TBCommon().ShowMessage(Page, "从淘宝下载数据失败。");
                return;
            }
            else
            {
                int PageNO = 1;
                if (_curBus._AllCountNO != null)
                {
                    PageNO = int.Parse(_curBus._AllCountNO) / 40;
                    if ((PageNO * 40).ToString() == _curBus._AllCountNO) { }
                    else
                        PageNO += 1;
                }
                for (int i = 2; i <= PageNO; i++)
                {
                    string[,] param2 = new string[,] { { "nick", user }, { "method", "taobao.trades.sold.get" }, 
                            { "fields", "tid,status,buyer_nick,price,created,num,orders" },{"status",status},{"start_created",start},{"end_created",end}, 
                            {"page_size","40"},{"page_no",i.ToString()},{ "v", "1.0" }, { "timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "format", "xml" },{"app_key",appkey}};
                    if (status == "ALL")
                        param2 = new string[,] { { "nick", user }, { "method", "taobao.trades.sold.get" }, 
                        { "fields", "tid,status,buyer_nick,price,created,num,orders" },{"start_created",start},{"end_created",end}, 
                        {"page_size","40"},{"page_no",i.ToString()},{ "v", "1.0" }, { "timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "format", "xml" },{"app_key",appkey}};


                    BS2.BSTaobaoAPI.BSTaobaoBussinessList bl = BS2.BSTaobaoAPI.BSTaobaoBussinessAPI.getTaobaoTrade(param2, appkey, certcode, sessionId);
                    if (bl.Count > 0)
                    {
                        foreach (BS2.BSTaobaoAPI.BSTaobaoBussiness bb in bl)
                        {
                            _curBus.Add(bb);
                        }
                    }
                }
            }
            List<GVTrade> tList = new List<GVTrade>();
            foreach (BS2.BSTaobaoAPI.BSTaobaoBussiness _cur in _curBus)
            {
                BS2.BSTaobaoAPI.BSTaobaoTrade _tt = (BS2.BSTaobaoAPI.BSTaobaoTrade)_cur;
                GVTrade t = new GVTrade();
                t.buyer_nick = _tt._buyer_nick;
                t.status = _tt._status;
                t.tid = _tt._tid;
                t.created = _tt._created;
                foreach (BS2.BSTaobaoAPI.BSTaobaoTrade_Order _o in _tt.Trade_Order)
                {
                    if (t.price==null)
                    {
                        t.price = _o._price;
                        
                    }
                    else
                    {
                        t.price += "," + _o._price;
                    }
                    if (t.num==null)
                    {
                        t.num = _o._num;                        
                    }
                    else
                    {
                        t.num += "," + _o._num;
                    }
                    if (t.title == null)
                    {
                        t.title = _o._title;
                    }
                    else
                    {
                        t.title += "," + _o._title;
                    }
                }                
                tList.Add(t);                
            }
            if(tList.Count>0)
            {
                DataTable mydt = new DataTable();
                mydt.Columns.Add("status");
                mydt.Columns.Add("buyer_nick");
                mydt.Columns.Add("price");
                mydt.Columns.Add("tid");
                mydt.Columns.Add("created");
                mydt.Columns.Add("num");
                mydt.Columns.Add("title");
                mydt.Columns.Add("note");
                foreach (GVTrade g in tList)
                {
                    //判断订单是否存在
                    if (!CheckTidisExist(g.tid, user))
                        mydt.Rows.Add(new string[] { g.status, g.buyer_nick, g.price, g.tid, g.created, g.num, g.title, g.note });
                }
                gvList.DataSource = mydt;
                gvList.DataBind();
            }
            else
            {
                //数据为空
                ltInfo.Text = "<b>当前没有可下载的订单，造成此情况的原因可能为：</b><br />";
                ltInfo.Text += "1)订单已经下载到本地数据库，为了节约时间，不重复下载；<br />";
                ltInfo.Text += "2)当前淘宝商店没有订单；<br />";
                ltInfo.Text += "3)您的搜索条件有误，请返回上一页面，重新设置搜索条件后重试。<br />";
                btnDown2.Enabled = false;
            }
        }
        catch
        {
            new TBCommon().ShowMessage(Page, "访问接口失败。");
            return;
        }
        #region
        //foreach (BS2.BSTaobaoAPI.BSTaobaoBussiness _cur in _curBus)
        //{
        //    BS2.BSTaobaoAPI.BSTaobaoTrade _tt = (BS2.BSTaobaoAPI.BSTaobaoTrade)_cur;
            
        //    //子定单列表  _tt.Trade_Order 
        //}
        //XmlDocument xml = BS2.BSTaobaoAPI.TaobaoAPI.getXmlFromTaobao(param);
        //if (xml == null || xml.OuterXml.Contains("error_rsp"))
        //{
        //    new TBCommon().ShowMessage(Page, "从淘宝下载数据失败。");
        //    return;
        //}
        //DataSet ds = new DataSet();
        //ds.ReadXml(new XmlNodeReader(xml));
        //if (ds != null && ds.Tables.Count > 0)
        //{
        //    List<GVTrade> tList = new List<GVTrade>();
        //    DataTable dt1 = ds.Tables["trade"];
        //    if (dt1 != null)
        //    {
        //        DataTable dt2 = ds.Tables["order"];
        //        for (int i = 0; i < dt1.Rows.Count; i++)
        //        {
        //            GVTrade t = new GVTrade();
        //            t.buyer_nick = dt1.Rows[i]["buyer_nick"].ToString();
        //            t.status = dt1.Rows[i]["status"].ToString();
        //            t.price = dt1.Rows[i]["price"].ToString();
        //            t.tid = dt1.Rows[i]["tid"].ToString();
        //            t.created = dt1.Rows[i]["created"].ToString();
        //            t.num = dt1.Rows[i]["num"].ToString();
        //            t.title = dt2.Rows[i]["title"].ToString();
        //            tList.Add(t);
        //        }
        //    }
        //    DataTable mydt = new DataTable();
        //    mydt.Columns.Add("status");
        //    mydt.Columns.Add("buyer_nick");
        //    mydt.Columns.Add("price");
        //    mydt.Columns.Add("tid");
        //    mydt.Columns.Add("created");
        //    mydt.Columns.Add("num");
        //    mydt.Columns.Add("title");
        //    mydt.Columns.Add("note");
        //    foreach (GVTrade g in tList)
        //    {
        //        //判断订单是否存在
        //        if(!CheckTidisExist(g.tid,user))
        //            mydt.Rows.Add(new string[] { g.status, g.buyer_nick, g.price, g.tid, g.created, g.num, g.title, g.note });
        //    }
        //    gvList.DataSource = mydt;
        //    gvList.DataBind();
        //}
        //else
        //{//数据为空
        //    ltInfo.Text = "<b>当前没有可下载的订单，造成此情况的原因可能为：</b><br />";
        //    ltInfo.Text += "1)订单已经下载到本地数据库，为了节约时间，不重复下载；<br />";
        //    ltInfo.Text += "2)当前淘宝商店没有订单；<br />";
        //    ltInfo.Text += "3)您的搜索条件有误，请返回上一页面，重新设置搜索条件后重试。<br />";
        //    btnDown2.Enabled = false;
        //}
        #endregion
    }
    #endregion

    #region 判断订单是否已经下载过
    /// <summary>
    /// 判断订单是否存在
    /// </summary> 
    bool CheckTidisExist(string tid, string username)
    {
        try
        {
            string ddly = null;
            string sql = "select ddly from tb_shangdian where tbzh='" + username + "'";
            DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
            ddly = ds.Tables[0].Rows[0][0].ToString();
            sql = "select count(*) from orderdoc where byzd18='" + tid + "' and order_ofcode='" + ddly + "'";
            if (DBUtility.SqlHelper.ExecuteCountSql(DBUtility.SqlHelper.LocalSqlServer, sql) > 0)
                return true;
        }
        catch
        {
        }
        return false;
    }
    #endregion

    #region 取得订单状态
    protected string GetTradeStatus(object o)
    {
        if (o is DBNull || o == null || o.ToString().Length == 0)
            return null;
        return new TBCommon().GetTradeStatus(o.ToString());
    }
    #endregion

    #region 下载订单到本地数据库
    protected void btnDown2_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in gvList.Rows)
        {
            CheckBox chk = (CheckBox)row.FindControl("chkOne");
            if (chk != null && chk.Checked)
            {
                int ret = new TB_Trade().DownTBTrade(txtUser.Text, txtpass.Text, new TaoBaoAPI().GetAppKey(txtUser.Text), new TaoBaoAPI().GetCertCode(txtUser.Text), txtSession.Text, row.Cells[4].Text);
                if (ret != 0)
                {
                    new TBCommon().ShowMessage(Page, "下载订单失败，错误代码："+ret.ToString());
                    return;
                }
            }
        }
        Response.Redirect("../order/orderlist.aspx");
    }
    #endregion
    protected void chkAll_OnCheckedChanged(object sender, EventArgs e)
    {
        new TBCommon().chk_OnCheckedChanged(sender, e, gvList, "chkOne");
    }
}
